package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryShopById(Long id) {
        String key = CACHE_SHOP_KEY + id;
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        String jsonShop = value.get(key);
        if (StrUtil.isNotBlank(jsonShop)) {
            return Result.ok(jsonShop);
        }
        if (jsonShop != null){
            return Result.ok("数据库中不存在该数据");
        }
        //加锁
        String lockKey = "lock:shop:" + id;
        try {
            //加锁失败
            if (!setLock(lockKey)){
                //回滚，查询缓存
                return queryShopById(id);
            }
            Shop shop = this.getById(id);
            if (shop == null){
                //当数据库中的数据不存在时，就缓存控制，避免缓存穿透的问题
                value.set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return Result.fail("商品信息不存在");
            }
            String jsonPrettyStr = JSONUtil.toJsonPrettyStr(shop);
            System.out.println("json格式的数据："+jsonPrettyStr);
            value.set(key, jsonPrettyStr,CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return Result.ok(jsonPrettyStr);
        }catch (Exception e){
             throw new RuntimeException(e);
        }finally {
             unlock(lockKey);
        }
    }

    public Boolean setLock(String key) {
        Boolean lock =
                stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10,TimeUnit.SECONDS);;
        return BooleanUtil.isTrue(lock);
    }
    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("商品不存在");
        }
        //1.更新数据库
        boolean b = updateById(shop);
        if (!b){
            return Result.fail("数据库更新失败");
        }
        //2.清除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }
}
